<template>
  <div class="admin-page admin-score-components">
    <div class="page-header">
      <h1>成绩组成设置</h1>
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/admin/teaching-mission/list' }">教学任务管理</el-breadcrumb-item>
          <el-breadcrumb-item>成绩组成设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <el-card class="info-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>教学任务信息</span>
        </div>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="教学任务编号">{{ teachingMission.code }}</el-descriptions-item>
        <el-descriptions-item label="课程名称">{{ teachingMission.courseName }}</el-descriptions-item>
        <el-descriptions-item label="学期">{{ teachingMission.termName }}</el-descriptions-item>
        <el-descriptions-item label="教师">
          <el-tag v-for="(name, index) in teachingMission.teacherNames" :key="index" size="small" class="teacher-tag">
            {{ name }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="队次">
          <el-tag v-for="(name, index) in teachingMission.classNames" :key="index" size="small" class="class-tag">
            {{ name }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否结课">
          <el-tag :type="teachingMission.isFinished ? 'success' : 'info'">
            {{ teachingMission.isFinished ? '已结课' : '未结课' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    
    <el-card class="component-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>成绩组成项目</span>
          <div class="header-actions">
            <el-button 
              type="success" 
              @click="openBatchCopyDialog"
              :disabled="scoreComponents.length === 0 || totalProportion !== 100"
              plain
            >
              <el-icon><DocumentCopy /></el-icon>
              批量复制
            </el-button>
            <el-button 
              type="primary" 
              @click="openCrossTermCopyDialog"
              :disabled="scoreComponents.length === 0 || totalProportion !== 100"
              plain
            >
              <el-icon><Switch /></el-icon>
              跨学期复制
            </el-button>
            <el-button 
              type="warning" 
              @click="openBatchSetDialog"
              plain
            >
              <el-icon><Setting /></el-icon>
              批量设置
            </el-button>
            <el-button type="primary" @click="openComponentDialog(null)">
              <el-icon><Plus /></el-icon> 添加成绩组成
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="component-summary" v-if="scoreComponents.length > 0">
        <el-alert
          :title="`总成绩组成比例: ${totalProportion}%`"
          :type="totalProportion === 100 ? 'success' : 'warning'"
          :description="totalProportion === 100 ? '成绩组成比例已达100%' : '成绩组成比例不等于100%，请调整各组成部分比例'"
          show-icon
          :closable="false"
        />
      </div>
      
      <el-table
        :data="scoreComponents"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="组成名称" min-width="150" resizable></el-table-column>
        <el-table-column prop="proportion" label="比例" width="100" resizable>
          <template #default="scope">
            {{ scope.row.proportion }}%
          </template>
        </el-table-column>
        <el-table-column prop="scoreTypeName" label="计分方式" width="120" resizable></el-table-column>
        <el-table-column label="考核性质" width="180" resizable>
          <template #default="scope">
            <el-tag 
              v-if="scope.row.examPartType === 'FORMATIVE'" 
              type="success" 
              size="small" 
              effect="plain" 
              style="margin-right: 5px;"
            >
              形成性
            </el-tag>
            <el-tag 
              v-if="scope.row.examPartType === 'FINAL'" 
              type="warning" 
              size="small" 
              effect="plain"
            >
              终结性
            </el-tag>
            <el-tag 
              v-if="scope.row.examPartType === 'OTHER'" 
              type="info" 
              size="small" 
              effect="plain"
            >
              其它
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" resizable>
          <template #default="scope">
            <el-button size="small" type="primary" @click="openComponentDialog(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteComponent(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="empty-placeholder" v-if="scoreComponents.length === 0">
        <el-empty description="暂无成绩组成项目">
          <el-button type="primary" @click="openComponentDialog(null)">添加成绩组成</el-button>
        </el-empty>
      </div>
    </el-card>
    
    <!-- 成绩组成表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="componentForm" 
        :model="componentForm" 
        :rules="rules" 
        label-width="120px"
      >
        <el-form-item label="组成名称" prop="name">
          <el-input v-model="componentForm.name" placeholder="请输入组成名称"></el-input>
        </el-form-item>
        
        <el-form-item label="比例(%)" prop="proportion">
          <el-input-number 
            v-model="componentForm.proportion" 
            :min="0" 
            :max="100" 
            :precision="0"
            controls-position="right"
            style="width: 100%;"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="计分方式" prop="scoreTypeId">
          <el-select v-model="componentForm.scoreTypeId" placeholder="选择计分方式" style="width: 100%;">
            <el-option 
              v-for="scoreType in scoreTypes" 
              :key="scoreType.id" 
              :label="scoreType.name" 
              :value="scoreType.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="考核性质" prop="examPartType">
          <el-select v-model="componentForm.examPartType" placeholder="请选择考核类型" style="width: 100%;">
            <el-option label="形成性考核" value="FORMATIVE" />
            <el-option label="终结性考核" value="FINAL" />
            <el-option label="其它" value="OTHER" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComponentForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 批量复制对话框 -->
    <ExamPartsCopyDialog
      v-model:visible="batchCopyDialogVisible"
      :source-mission="teachingMission"
      @copy-success="handleBatchCopySuccess"
    />
    
    <!-- 跨学期复制对话框 -->
    <CrossTermCopyDialog
      v-model:visible="crossTermCopyDialogVisible"
      :source-mission-id="teachingMission.id"
      @completed="handleCrossTermCopySuccess"
    />
    
    <!-- 批量设置对话框 -->
    <BatchSetExamPartsDialog
      v-model:visible="batchSetDialogVisible"
      @completed="handleBatchSetSuccess"
    />
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { teachingMissionApi } from '@/api/teaching-mission'
import { courseExamPartApi } from '@/api/course-exam-part'
import { scoreTypeApi } from '@/api/base-data'
import { Plus, Edit, Delete, DocumentCopy, Switch, Setting } from '@element-plus/icons-vue'
import ExamPartsCopyDialog from '@/components/teaching-mission/dialogs/ExamPartsCopyDialog.vue'
import CrossTermCopyDialog from '@/components/teaching-mission/dialogs/CrossTermCopyDialog.vue'
import BatchSetExamPartsDialog from '@/components/teaching-mission/dialogs/BatchSetExamPartsDialog.vue'

export default {
  components: {
    Plus, Edit, Delete, DocumentCopy, Switch, Setting,
    ExamPartsCopyDialog,
    CrossTermCopyDialog,
    BatchSetExamPartsDialog
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const teachingMissionId = computed(() => route.params.id)
    
    // 数据加载状态
    const loading = ref(false)
    
    // 教学任务信息 - 使用标准TeachingMissionDTO字段结构
    const teachingMission = ref({
      id: null,
      code: '',
      courseId: null,
      courseName: '',
      courseCode: '',
      termId: null,
      termName: '',
      teacherIds: [],
      teacherNames: [],
      classIds: [],
      classNames: [],
      isFinished: false,
      remark: ''
    })
    
    // 成绩组成数据
    const scoreComponents = ref([])
    
    // 计分方式选项
    const scoreTypes = ref([])
    
    // 计算总比例
    const totalProportion = computed(() => {
      return scoreComponents.value.reduce((sum, component) => sum + component.proportion, 0)
    })
    
    // 对话框状态和表单数据
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)
    const componentForm = reactive({
      id: null,
      name: '',
      proportion: 0,
      scoreTypeId: null,
      examPartType: 'FORMATIVE',
      teachingMissionId: null
    })
    
    // 新对话框状态
    const batchCopyDialogVisible = ref(false)
    const crossTermCopyDialogVisible = ref(false)
    const batchSetDialogVisible = ref(false)
    
    // 表单验证规则
    const rules = {
      name: [{ required: true, message: '请输入组成名称', trigger: 'blur' }],
      proportion: [{ required: true, message: '请输入比例', trigger: 'blur' }],
      scoreTypeId: [{ required: true, message: '请选择计分方式', trigger: 'change' }]
    }
    
    // 获取教学任务详情
    const fetchTeachingMission = async () => {
      loading.value = true
      try {
        const response = await teachingMissionApi.getTeachingMissionById(teachingMissionId.value)
        teachingMission.value = response.data
      } catch (error) {
        console.error('获取教学任务详情失败:', error)
        ElMessage.error('获取教学任务详情失败')
        // 如果获取失败，返回到教学任务列表页面
        router.push('/admin/teaching-mission/list')
      } finally {
        loading.value = false
      }
    }
    
    // 获取成绩组成列表
    const fetchScoreComponents = async () => {
      loading.value = true
      try {
        const response = await courseExamPartApi.getExamPartsByTeachingMission(teachingMissionId.value)
        scoreComponents.value = response.data
      } catch (error) {
        console.error('获取成绩组成列表失败:', error)
        ElMessage.error('获取成绩组成列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取计分方式列表
    const fetchScoreTypes = async () => {
      try {
        const response = await scoreTypeApi.getAllScoreTypes()
        scoreTypes.value = Array.isArray(response.data) ? response.data : []
      } catch (error) {
        console.error('获取计分方式列表失败:', error)
        ElMessage.error('获取计分方式列表失败')
      }
    }
    
    // 打开成绩组成对话框
    const openComponentDialog = (component) => {
      resetForm()
      
      // 自动设置教学任务ID
      componentForm.teachingMissionId = teachingMissionId.value
      
      if (component) {
        isEdit.value = true
        dialogTitle.value = '编辑成绩组成'
        
        // 填充表单数据
        componentForm.id = component.id
        componentForm.name = component.name
        componentForm.proportion = component.proportion
        componentForm.scoreTypeId = component.scoreTypeId
        componentForm.examPartType = component.examPartType
        componentForm.teachingMissionId = teachingMissionId.value
      } else {
        isEdit.value = false
        dialogTitle.value = '添加成绩组成'
      }
      
      dialogVisible.value = true
    }
    
    // 提交成绩组成表单
    const submitComponentForm = async () => {
      // 表单验证
      const componentFormEl = document.querySelector('.el-form')
      if (!componentFormEl) return
      
      componentFormEl.validate(async (valid) => {
        if (valid) {
          try {
            if (isEdit.value) {
              // 编辑模式
              await courseExamPartApi.updateExamPart(componentForm.id, componentForm)
              ElMessage.success('更新成绩组成成功')
            } else {
              // 新增模式
              await courseExamPartApi.createExamPart(componentForm)
              ElMessage.success('添加成绩组成成功')
            }
            
            // 刷新数据和关闭对话框
            dialogVisible.value = false
            fetchScoreComponents()
          } catch (error) {
            console.error('保存成绩组成失败:', error)
            ElMessage.error('保存成绩组成失败')
          }
        }
      })
    }
    
    // 删除成绩组成
    const deleteComponent = (component) => {
      ElMessageBox.confirm(`确定要删除成绩组成"${component.name}"吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await courseExamPartApi.deleteExamPart(component.id)
          ElMessage.success('删除成绩组成成功')
          fetchScoreComponents()
        } catch (error) {
          console.error('删除成绩组成失败:', error)
          ElMessage.error('删除成绩组成失败')
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    }
    
    // 打开批量复制对话框
    const openBatchCopyDialog = () => {
      batchCopyDialogVisible.value = true
    }
    
    // 打开跨学期复制对话框
    const openCrossTermCopyDialog = () => {
      crossTermCopyDialogVisible.value = true
    }
    
    // 打开批量设置对话框
    const openBatchSetDialog = () => {
      batchSetDialogVisible.value = true
    }
    
    // 处理批量复制成功回调
    const handleBatchCopySuccess = (copiedCount) => {
      ElMessage.success(`成功复制考核方案到 ${copiedCount} 个教学任务`)
      batchCopyDialogVisible.value = false
    }
    
    // 处理跨学期复制成功回调
    const handleCrossTermCopySuccess = () => {
      ElMessage.success('跨学期复制考核方案成功')
      crossTermCopyDialogVisible.value = false
    }
    
    // 处理批量设置成功回调
    const handleBatchSetSuccess = () => {
      ElMessage.success('批量设置考核组成成功')
      batchSetDialogVisible.value = false
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(componentForm, {
        id: null,
        name: '',
        proportion: 0,
        scoreTypeId: null,
        examPartType: 'FORMATIVE',
        teachingMissionId: null
      })
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      fetchTeachingMission()
      fetchScoreComponents()
      fetchScoreTypes()
    })
    
    return {
      teachingMission,
      loading,
      scoreComponents,
      scoreTypes,
      totalProportion,
      dialogVisible,
      dialogTitle,
      isEdit,
      componentForm,
      rules,
      openComponentDialog,
      submitComponentForm,
      deleteComponent,
      batchCopyDialogVisible,
      crossTermCopyDialogVisible,
      batchSetDialogVisible,
      openBatchCopyDialog,
      openCrossTermCopyDialog,
      openBatchSetDialog,
      handleBatchCopySuccess,
      handleCrossTermCopySuccess,
      handleBatchSetSuccess
    }
  }
}
</script>

<style scoped>
.admin-score-components .page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.admin-score-components .page-header h1 {
  margin: 0;
  font-size: 24px;
}

.info-card {
  margin-bottom: 20px;
}

.component-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.teacher-tag,
.class-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.component-summary {
  margin-bottom: 20px;
}

.empty-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.header-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-actions .el-button {
  margin: 0;
}
</style>
